package com.chungkui.bond.authmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chungkui.bond.authmanager.bean.Client;
import com.chungkui.bond.authmanager.bean.Permission;
import com.chungkui.bond.authmanager.mapper.ClientMapper;
import com.chungkui.bond.authmanager.service.BondLineService;
import com.chungkui.bond.authmanager.service.ClientService;
import com.chungkui.bond.authmanager.service.PermissionService;
import com.chungkui.bond.common.core.bean.BondNode;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;


@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements ClientService {
    private final static Logger LOG = LoggerFactory.getLogger(ClientServiceImpl.class);

    @Autowired
    private BondLineService bondLineService;
    @Autowired
    private PermissionService permissionService;

    @Override
    @Transactional
    public void saveBondNodeInfos(BondNode node) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("start_point", node.getId());
        bondLineService.remove(queryWrapper);
        bondLineService.saveBatch(node.getBondLines());
        List<Permission> permissions = parserUrl2permission(node);
        if (CollectionUtils.isNotEmpty(permissions)) {
            permissionService.saveBatchByUrlAndClientId(permissions);
        }

    }

    private List<Permission> parserUrl2permission(BondNode node) {
        List<Map<String, String>> urls = node.getUrls();
        List<Permission> permissions = Lists.newArrayList();
        if (CollectionUtils.isNotEmpty(urls)) {
            for (Map<String, String> url : urls) {
                for (String key : url.keySet()) {
                    Permission permission = new Permission();
                    permission.setUrl(key);
                    permission.setName(url.get(key));
                    permission.setClientId(node.getId());
                    permissions.add(permission);
                }

            }
        }
        return permissions;
    }
}
